<template>
  <div class="user-management">
    <div class="page-header">
      <h1>用户管理</h1>
      <p>管理系统中的所有用户账户</p>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" @submit.prevent="handleSearch" inline>
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入姓名"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="选择角色" clearable style="width: 120px">
            <el-option label="学生" value="student" />
            <el-option label="教师" value="teacher" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
          <el-button type="success" @click="handleAdd" :icon="Plus">添加用户</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <div>
            <el-tag>共 {{ total }} 个用户</el-tag>
          </div>
        </div>
      </template>

      <el-table 
        :data="users" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="email" label="邮箱" min-width="200" />
        <el-table-column label="角色" width="100">
          <template #default="scope">
            <el-tag 
              :type="getRoleType(scope.row.role)"
              size="small"
            >
              {{ getRoleText(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="150">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="last_login" label="最后登录" width="150">
          <template #default="scope">
            {{ scope.row.last_login ? formatDate(scope.row.last_login) : '从未登录' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag 
              :type="scope.row.is_active ? 'success' : 'danger'"
              size="small"
            >
              {{ scope.row.is_active ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              :type="scope.row.is_active ? 'warning' : 'success'"
              size="small"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.is_active ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.role === 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedUsers.length > 0">
      <el-card>
        <div class="batch-content">
          <span>已选择 {{ selectedUsers.length }} 个用户</span>
          <div class="batch-buttons">
            <el-button 
              type="warning" 
              @click="handleBatchDisable"
            >
              批量禁用
            </el-button>
            <el-button 
              type="success" 
              @click="handleBatchEnable"
            >
              批量启用
            </el-button>
            <el-button 
              type="danger" 
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
            <el-button @click="clearSelection">取消选择</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="editDialog.visible"
      :title="editDialog.title"
      width="600px"
    >
      <el-form 
        :model="editDialog.form" 
        :rules="editRules" 
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="editDialog.form.username" 
            :disabled="editDialog.mode === 'edit'"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editDialog.form.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editDialog.form.email" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editDialog.form.role" style="width: 100%">
            <el-option label="学生" value="student" />
            <el-option label="教师" value="teacher" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editDialog.mode === 'add'" label="密码" prop="password">
          <el-input 
            type="password" 
            v-model="editDialog.form.password" 
            show-password
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch 
            v-model="editDialog.form.is_active" 
            active-text="启用" 
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialog.visible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmit"
            :loading="editDialog.loading"
          >
            {{ editDialog.mode === 'add' ? '创建' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { getAllUsers, createUser, updateUser, deleteUser } from '@/api/user'

const loading = ref(false)
const users = ref([])
const total = ref(0)
const selectedUsers = ref([])
const editFormRef = ref(null)

const searchForm = reactive({
  username: '',
  name: '',
  role: ''
})

const pagination = reactive({
  page: 1,
  limit: 20
})

const editDialog = reactive({
  visible: false,
  title: '',
  mode: 'add', // 'add' | 'edit'
  loading: false,
  form: {
    username: '',
    name: '',
    email: '',
    role: 'student',
    password: '',
    is_active: true
  }
})

const editRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在 3-20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为 6 位', trigger: 'blur' }
  ]
}

// 获取角色类型
const getRoleType = (role) => {
  switch (role) {
    case 'admin': return 'danger'
    case 'teacher': return 'warning'
    case 'student': return 'success'
    default: return ''
  }
}

// 获取角色文本
const getRoleText = (role) => {
  switch (role) {
    case 'admin': return '管理员'
    case 'teacher': return '教师'
    case 'student': return '学生'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true
    const params = {
      ...pagination,
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getAllUsers(params)
    if (response.code === 0) {
      users.value = response.data.users
      total.value = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchUsers()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.page = 1
  fetchUsers()
}

// 添加用户
const handleAdd = () => {
  editDialog.mode = 'add'
  editDialog.title = '添加用户'
  editDialog.form = {
    username: '',
    name: '',
    email: '',
    role: 'student',
    password: '',
    is_active: true
  }
  editDialog.visible = true
}

// 编辑用户
const handleEdit = (user) => {
  editDialog.mode = 'edit'
  editDialog.title = '编辑用户'
  editDialog.form = {
    id: user.id,
    username: user.username,
    name: user.name,
    email: user.email,
    role: user.role,
    is_active: user.is_active
  }
  editDialog.visible = true
}

// 提交表单
const handleSubmit = () => {
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      editDialog.loading = true
      try {
        if (editDialog.mode === 'add') {
          const response = await createUser(editDialog.form)
          if (response.code === 0) {
            ElMessage.success('用户创建成功！')
            editDialog.visible = false
            fetchUsers()
          }
        } else {
          const response = await updateUser(editDialog.form.id, editDialog.form)
          if (response.code === 0) {
            ElMessage.success('用户更新成功！')
            editDialog.visible = false
            fetchUsers()
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
      } finally {
        editDialog.loading = false
      }
    }
  })
}

// 切换用户状态
const handleToggleStatus = async (user) => {
  const action = user.is_active ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}用户 "${user.name}" 吗？`,
      `${action}用户`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await updateUser(user.id, {
      is_active: !user.is_active
    })

    if (response.code === 0) {
      ElMessage.success(`用户${action}成功！`)
      user.is_active = !user.is_active
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换用户状态失败:', error)
    }
  }
}

// 删除用户
const handleDelete = async (user) => {
  if (user.role === 'admin') {
    ElMessage.warning('无法删除管理员用户')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.name}" 吗？此操作不可恢复！`,
      '删除用户',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteUser(user.id)
    if (response.code === 0) {
      ElMessage.success('用户删除成功！')
      fetchUsers()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
    }
  }
}

// 批量禁用
const handleBatchDisable = async () => {
  const enabledUsers = selectedUsers.value.filter(user => user.is_active)
  if (enabledUsers.length === 0) {
    ElMessage.info('没有可禁用的用户')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要禁用这 ${enabledUsers.length} 个用户吗？`,
      '批量禁用',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const promises = enabledUsers.map(user => 
      updateUser(user.id, { is_active: false })
    )

    await Promise.all(promises)
    ElMessage.success(`成功禁用 ${enabledUsers.length} 个用户`)
    fetchUsers()
    clearSelection()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量禁用失败:', error)
    }
  }
}

// 批量启用
const handleBatchEnable = async () => {
  const disabledUsers = selectedUsers.value.filter(user => !user.is_active)
  if (disabledUsers.length === 0) {
    ElMessage.info('没有可启用的用户')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要启用这 ${disabledUsers.length} 个用户吗？`,
      '批量启用',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const promises = disabledUsers.map(user => 
      updateUser(user.id, { is_active: true })
    )

    await Promise.all(promises)
    ElMessage.success(`成功启用 ${disabledUsers.length} 个用户`)
    fetchUsers()
    clearSelection()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量启用失败:', error)
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  const deletableUsers = selectedUsers.value.filter(user => user.role !== 'admin')
  if (deletableUsers.length === 0) {
    ElMessage.info('没有可删除的用户（管理员无法删除）')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除这 ${deletableUsers.length} 个用户吗？此操作不可恢复！`,
      '批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const promises = deletableUsers.map(user => deleteUser(user.id))
    await Promise.all(promises)
    ElMessage.success(`成功删除 ${deletableUsers.length} 个用户`)
    fetchUsers()
    clearSelection()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
    }
  }
}

// 分页处理
const handleSizeChange = () => {
  pagination.page = 1
  fetchUsers()
}

const handleCurrentChange = () => {
  fetchUsers()
}

// 表格选择处理
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

const clearSelection = () => {
  selectedUsers.value = []
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-management {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 28px;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #909399;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.batch-actions {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
}

.batch-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px 16px;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

:deep(.el-table) {
  font-size: 14px;
}
</style> 